package com.mactivity.activities;

import java.util.ArrayList;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mactivity.helper.Constants;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.mactivity.database.AddFriendActivityFunctions;
import com.mactivity.helper.SharedPreferenceHelper;

/*
 * 
 * This class handles all the details regarding adding a friend
 * 
 * 
 */
public class AddFriendActivity extends Activity implements OnClickListener
{
	//Declarations
	SharedPreferenceHelper preferenceHelper;
	EditText frEmail;
	Button submit,search;
	private int addingYourself=0,alreadyFriends=0,notificationResult=0;
	private Integer I;
	private String myId,userId,myName,myEmailAdd,friendEmail,clickedEmail,user,receivedData;
	private ArrayList<String>emailValues= new ArrayList<String>();
	ArrayAdapter<String> adapter;
	ListView emailList;
	boolean check=false,friends=false,notification=false;
	AddFriendActivityFunctions  addFriendActivityFunction;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
    	.detectDiskReads().detectDiskWrites().detectNetwork() // or	.detectAll() for all detectable problems
		.penaltyLog().build());
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.add_friend);
        
        //SharedPreferenceHelper class which helps retrieve logged in user's information
        preferenceHelper =  new SharedPreferenceHelper(this);
        Map<String, String> userInfo=preferenceHelper.getUserInformation();
 		I=new Integer(Integer.parseInt(userInfo.get(Constants.USER_ID)));
 		addFriendActivityFunction= new AddFriendActivityFunctions();
 		
 		//Retrieves Current User's Email Id
 		myEmailAdd=userInfo.get(Constants.USER_EMAIL_ID);
 		
 		//Retrieves Current User's Email Id
 		myName=userInfo.get(Constants.USER_NAME);
 		
 		//fetching entered email id
 		frEmail = (EditText) findViewById(R.id.emailId);
 		search = (Button) findViewById(R.id.searchfriend);
        myId=I+"";   
        search.setOnClickListener(this);
        
    }
    public void onClick(View v)
    {
    	if(v.getId()==R.id.searchfriend)
    	{
 
    		emailValues.clear();
    		String checkUser;
    		friendEmail=frEmail.getText().toString()+"%";
    		// this function call is to check if the user is valid user
    		checkUser=addFriendActivityFunction.findUser(friendEmail);
    		checkUser= checkUser.replaceAll("\\s+", "");
    		try
    		{
    			if(checkUser.equals("null"))
    			{
    				Toast.makeText(this, "Invalid user "+ frEmail.getText().toString(),
    						Toast.LENGTH_LONG).show();
    			}
    			else
    			{
    				receivedData = "";
    				JSONArray jArray = new JSONArray(checkUser);
    				JSONObject json_data;
    				for(int i=0;i<jArray.length();i++)
    				{
    					json_data = jArray.getJSONObject(i);
    					emailValues.add(json_data.getString(Constants.JSON_STRING_EMAIL));
    					check=true;
    					receivedData += "\n" + json_data.getString(Constants.JSON_STRING_NAME)+json_data.getString(Constants.JSON_STRING_EMAIL);
    				}
    			}
    			adapter=new ArrayAdapter<String>(this,
    					android.R.layout.simple_list_item_1,
    					emailValues);
    			emailList = (ListView) findViewById(R.id.userList);
    			emailList.setAdapter(adapter);
    			emailList.setTextFilterEnabled(true);
    			emailList.setOnItemClickListener(new OnItemClickListener(){
    				
    				@Override
    				/*
    				 * This method fetches the information about the clicked item in the listview 
    				 * and asks if user wants to add as a friend 
    				 * 
    				 */
    				public void onItemClick(AdapterView<?> parent,
    						View view, int position, long id) {
    					String clickedUsersId;
    					clickedEmail= emailValues.get(position);
    					System.out.println("Clicked Email: "+clickedEmail);
    					//find out Id of clicked email
    					clickedUsersId=addFriendActivityFunction.fetchId(clickedEmail);
    					clickedUsersId= clickedUsersId.replaceAll("\\s+", "");
    					userId="";
    					try
    					{
    						receivedData = "";
    						JSONArray jArray = new JSONArray(clickedUsersId);
    						for(int i=0;i<jArray.length();i++)
    						{
    							JSONObject json_data = jArray.getJSONObject(i);
    							userId=json_data.getInt(Constants.COLUMN_USER_ID)+"";
    							user=json_data.getString(Constants.COLUMN_USER_NAME)+"";
    							System.out.println(userId+" :userId");
    							receivedData += "\n" + json_data.getInt(Constants.COLUMN_USER_ID)+" ->"+json_data.getString(Constants.COLUMN_USER_NAME);
    						}
    					}
    					catch(JSONException e)
    					{
    						Log.e("log_tag", "Error parsing data "+e.toString());
    					}
    					
    					//find if they are friends already
    					String friendCheck;
    					friendCheck=addFriendActivityFunction.checkIfFriends(I.toString(), userId);
    					friendCheck= friendCheck.replaceAll("\\s+", "");
    					if ((Integer.parseInt(friendCheck))==0)
    					{
    						friends=false;
    					}
    					else //means they are friends already
    					{
    						friends=true;
    					}
    					if((Integer.parseInt(friendCheck))==0)  //if friendCheck==null
    					{
    						String seeIfFriends;
    						// check other way around
    						seeIfFriends=addFriendActivityFunction.checkIfFriends(userId,I.toString());
    						seeIfFriends= seeIfFriends.replaceAll("\\s+", "");
    						System.out.println("seeIfFriends"+seeIfFriends); 
    						if (seeIfFriends.equals("0"))//not friends
    						{
    							alreadyFriends=1;
    							System.out.println("alreadyFriends set"+friends);
    						}
    						else //(!(seeIfFriends.equals("0")))//means they are friends already
    						{
    							friends=true;
    						}//if(!(seeIfFriends.equals("0"))) 
    						
    					}//if((Integer.parseInt(friendCheck))==0)
    						
    					
    					//check if notification sent already
    					
    					String checkNotification=addFriendActivityFunction.checkNotification(myId, userId);
    					checkNotification= checkNotification.replaceAll("\\s+", "");
    					
    					
    					if ((Integer.parseInt(checkNotification))==0)
    					{
    						
    						notification=false;
    						
    					}
    					else//means notifications sent already
    					{
    						notification=true;
    					}//if((Integer.parseInt(friendCheck))==1) closed
    					if((Integer.parseInt(checkNotification))==0)  //if friendCheck==null
    					{
    						// check other way around, result contains if the other wat around notification has been sent
    						String result;
    						result=addFriendActivityFunction.checkNotification(userId, myId);
    						result= result.replaceAll("\\s+", "");
    						notificationResult=(Integer.parseInt(result));
    						if (notificationResult==0)
    						{
    							System.out.println("notification already sent");
    						}
    						else//if(notificationResult==1)//means notifications sent already
    						{
    							notification=true;
    						}    				
    						
    					}
    					AlertDialog alert= new AlertDialog.Builder(AddFriendActivity.this).create();
    					alert.setTitle("ADD FRIEND");
    					alert.setMessage("Add "+user+" as friend");
    					alert.setButton("Cancel", new DialogInterface.OnClickListener() {
    						@Override
    						public void onClick(DialogInterface dialog, int which) {
    							// TODO Auto-generated method stub
    						}
    					});
    					alert.setButton2("Add Friend", new DialogInterface.OnClickListener() {
    						@Override
    						public void onClick(DialogInterface dialog, int which) {
    							//  adding friend logic
    							addingYourself=0;alreadyFriends=0;
    							if(clickedEmail.equals(myEmailAdd))
    							{
    								//you are trying to add yourself
    								addingYourself=1;
    								System.out.println("Adding yourself");
    								AlertDialog alert1= new AlertDialog.Builder(AddFriendActivity.this).create();
    								alert1.setTitle("");
    								alert1.setMessage("Trying to add yourself as friend");
    								alert1.setButton("Cancel", new DialogInterface.OnClickListener() {
    									@Override
    									public void onClick(DialogInterface dialog, int which) {
    										// TODO Auto-generated method stub
    									}
    								});
    								alert1.show();
    							}
    						
    							if(friends==true&&addingYourself==0)
    							{
    								//they are friends already
    								System.out.println("Friends Already");
    								alreadyFriends=1;
    								AlertDialog alert2= new AlertDialog.Builder(AddFriendActivity.this).create();
    								alert2.setTitle("Already Friends");
    								alert2.setMessage(myName+" and "+user+" are friends already");
    								alert2.setButton("OK", new DialogInterface.OnClickListener() {
    									@Override
    									public void onClick(DialogInterface dialog, int which) {
    										// TODO Auto-generated method stub
    									}
    								});
    								alert2.show();
    							}
    							if(notification==true&&alreadyFriends==0&&addingYourself==0)
    							{
    								//notification already there
    								System.out.println("Notification in there");
    								AlertDialog alert3= new AlertDialog.Builder(AddFriendActivity.this).create();
    								alert3.setTitle("Notification");
    								alert3.setMessage("Request is already sent");
    								alert3.setButton("OK", new DialogInterface.OnClickListener() {
    									@Override
    									public void onClick(DialogInterface dialog, int which) {
    										// TODO Auto-generated method stub
    									}
    								});
    								alert3.show();
    							}
    							if(notification==false&&alreadyFriends==0&&addingYourself==0)
    							{
    								//insert in notification relation
    								String insertResult;
    								insertResult=addFriendActivityFunction.addNotification(myId, userId);
    								insertResult= insertResult.replaceAll("\\s+", "");
    								System.out.println(insertResult+" insertResult");
    								if(insertResult.equals("1"))
    								{
    									System.out.println("Friend Request Sent ");
    									AlertDialog alert4= new AlertDialog.Builder(AddFriendActivity.this).create();
    									alert4.setTitle("Friend Request");
    									alert4.setMessage("Friend Request sent");
    									alert4.setButton("OK", new DialogInterface.OnClickListener() {
    										@Override
    										public void onClick(DialogInterface dialog, int which) {
    											// TODO Auto-generated method stub
    										}
    									});
    									alert4.show();
    								}
    								
    							}
    						}
    					});
    					alert.show();
    				}
    			});
    		}
    		catch(Exception ee)
    		{
    			ee.printStackTrace();
    		}
    	}//switch ends
}//onclick ends
    /*
     * This onbackPressed() is overridden and it takes the navigation to the Home Page
     * 
     * 
     */
@Override
public void onBackPressed()
{
	Intent back=new Intent(AddFriendActivity.this,HomeActivity.class);
	startActivity(back);
	finish();
}
}//main class ends
